<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <FeatherIcon name="chevron-left" size="24" color="#333" />
      </view>
      <view class="title">发布帖子</view>
      <view class="draft-btn" @click="navigateToDrafts">
        草稿({{ draftCount }})
      </view>
    </view>

    <scroll-view scroll-y class="content">
      <view class="form-container">
        <!-- 标题输入 -->
        <view class="form-item">
          <input
            class="title-input"
            v-model="formData.articleTitle"
            placeholder="请输入标题"
            maxlength="100"
          />
        </view>

        <!-- Markdown编辑器 -->
        <view class="form-item content-item">
          <view v-if="!isPreview" class="editor-container">
            <textarea
              class="content-textarea"
              v-model="formData.articleContent"
              placeholder="支持 Markdown 语法,分享你的想法..."
              :maxlength="-1"
              @input="handleInput"
              :cursor-spacing="120"
              :show-confirm-bar="false"
              :cursor="cursorPosition"
              @focus="handleFocus"
              :style="{ width: '100%', boxSizing: 'border-box' }"
            />
          </view>
          <view v-else class="preview-container">
            <rich-text
              :nodes="previewContent"
              class="preview-content"
            ></rich-text>
          </view>

          <!-- 移动到下方的工具栏 -->
          <view class="editor-toolbar">
            <view class="toolbar-left">
              <view class="toolbar-btn" @click="handleUploadImage">
                <FeatherIcon name="image" size="20" color="#666" />
              </view>
              <view class="toolbar-btn" @click="insertMarkdown('**', '**')">
                <FeatherIcon name="bold" size="20" color="#666" />
              </view>
              <view class="toolbar-btn" @click="insertMarkdown('*', '*')">
                <FeatherIcon name="italic" size="20" color="#666" />
              </view>
              <view class="toolbar-btn" @click="insertMarkdown('# ', '')">
                <FeatherIcon name="type" size="20" color="#666" />
              </view>
              <view class="toolbar-btn" @click="insertMarkdown('- ', '')">
                <FeatherIcon name="list" size="20" color="#666" />
              </view>
              <view class="toolbar-btn" @click="insertMarkdown('[', '](url)')">
                <FeatherIcon name="link" size="20" color="#666" />
              </view>
            </view>
            <view class="toolbar-right">
              <view class="preview-btn" @click="togglePreview">
                {{ isPreview ? "编辑" : "预览" }}
              </view>
            </view>
          </view>
        </view>

        <!-- 标签输入 -->
        <view class="form-item tags-item">
          <view class="tags-header">
            <text class="section-title">添加标签</text>
            <text class="tags-tip">（请使用逗号分隔每个标签，最多 4 个）</text>
          </view>

          <!-- 已选择的标签展示 -->
          <view class="selected-tags" v-if="selectedTags.length > 0">
            <view
              class="tag-item"
              v-for="(tag, index) in selectedTags"
              :key="index"
            >
              {{ tag }}
              <view class="tag-remove" @click="removeTag(index)">×</view>
            </view>
          </view>

          <!-- 标签输入框 -->
          <input
            class="tags-input"
            v-model="tagInput"
            placeholder="输入标签并回车，或选择下方标签"
            @confirm="addTag"
            @blur="handleTagInputBlur"
          />

          <!-- 历史和推荐标签 -->
          <view class="tags-suggestion">
            <view class="suggestion-header">
              <view class="suggestion-title">历史标签：</view>
              <view
                class="clear-all"
                @click="clearAllHistoricalTags"
                v-if="historicalTags.length > 0"
                >清空</view
              >
            </view>
            <view class="suggestion-list">
              <view
                class="suggestion-tag"
                v-for="(tag, index) in historicalTags"
                :key="'history-' + index"
              >
                <text @click="selectTag(tag)">{{ tag }}</text>
                <text
                  class="delete-tag"
                  @click.stop="deleteHistoricalTag(index)"
                  >×</text
                >
              </view>
            </view>

            <view class="suggestion-title">推荐标签：</view>
            <view class="suggestion-list">
              <view
                class="suggestion-tag"
                v-for="(tag, index) in recommendedTags"
                :key="'recommend-' + index"
                @click="selectTag(tag)"
              >
                {{ tag }}
              </view>
            </view>
          </view>
        </view>

        <!-- 打赏区 -->
        <view class="form-item reward-settings">
          <view class="section-title">打赏区</view>
          <view class="reward-content">
            <textarea
              class="reward-textarea"
              v-model="formData.articleRewardContent"
              placeholder="1. 当设置了打赏积分后，将启用打赏功能
2. 启用打赏需要 20 积分
3. 打赏区的内容只有在浏览者打赏后才对其可见"
            />
          </view>
          <view class="reward-point">
            <text class="reward-label">打赏积分</text>
            <input
              class="point-input"
              type="number"
              v-model="formData.articleRewardPoint"
              placeholder="请输入打赏积分"
            />
          </view>
        </view>

        <!-- 基础设置 -->
        <view class="form-item basic-settings">
          <view class="section-title">基础设置</view>
          <view class="radio-group">
            <view class="radio-item">
              <radio
                :checked="formData.articleShowInList"
                @click="
                  formData.articleShowInList = !formData.articleShowInList
                "
                color="#ff9800"
              />
              <text class="radio-label">显示在列表</text>
            </view>
            <view class="radio-item">
              <radio
                :checked="formData.articleCommentable"
                @click="
                  formData.articleCommentable = !formData.articleCommentable
                "
                color="#ff9800"
              />
              <text class="radio-label">允许评论</text>
            </view>
            <view class="radio-item">
              <radio
                :checked="formData.articleIsOriginal"
                @click="
                  formData.articleIsOriginal = !formData.articleIsOriginal
                "
                color="#ff9800"
              />
              <text class="radio-label">原创内容</text>
            </view>
            <view class="radio-item">
              <radio
                :checked="formData.articleAnonymous"
                @click="formData.articleAnonymous = !formData.articleAnonymous"
                color="#ff9800"
              />
              <text class="radio-label">匿名发布</text>
            </view>
            <view class="radio-item">
              <radio
                :checked="formData.articleNotifyFollowers"
                @click="
                  formData.articleNotifyFollowers =
                    !formData.articleNotifyFollowers
                "
                color="#ff9800"
              />
              <text class="radio-label">通知关注者</text>
            </view>

            <view class="radio-item">
              <!-- <radio
                :checked="formData.articleNotifyFollowers"
                @click="
                  formData.articleNotifyFollowers =
                    !formData.articleNotifyFollowers
                "
                color="#ff9800"
              /> -->
              <text class="radio-label"> </text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部发布按钮 -->
    <view class="bottom-bar">
      <view class="btn-group">
        <button class="draft-save-btn" @click="saveDraft">保存草稿</button>
        <button class="submit-btn" @click="handleSubmit">发布</button>
      </view>
    </view>

    <!-- 积分奖励提示框 -->
    <view class="reward-dialog" v-if="showRewardDialog">
      <view class="dialog-content">
        <view class="dialog-header">
          <text class="dialog-title">积分奖励说明</text>
          <view class="close-btn" @click="closeRewardDialog">
            <FeatherIcon name="x" size="24" color="#999" />
          </view>
        </view>
        <view class="dialog-body">
          <view class="reward-info">
            <text class="reward-title"
              >根据摸鱼派发帖规范细则，请对您的帖子进行自觉分类，自行选择是否获得好帖积分和活跃度奖励
              (300积分和45%活跃度，每日仅第一次有效)</text
            >

            <view class="reward-section">
              <text class="section-title">有积分奖励的帖子：</text>
              <text class="section-content"
                >原创的技术文章 / 原创且用心的美食、旅游、生活内容 /
                发自内心的分享 / 有营养的问答 /
                原创且用心的长短篇小说、故事、纪实创作</text
              >
            </view>

            <view class="reward-section">
              <text class="section-title">没有积分奖励的帖子：</text>
              <text class="section-content"
                >发牢骚、感慨 / 非原创的内容 / 无意义内容帖、单纯的水帖 /
                新人报道帖 / 广告帖 /
                不用心、无价值的长短篇小说、故事、纪实创作</text
              >
            </view>

            <text class="reward-note"
              >请注意：帖子发布后24小时内无法删除！如果不知道该选哪个，请选"我就随便写写"，选择领取奖励后，我们将对帖子进行检查，如不符合规则，您的积分奖励将会被扣除。</text
            >
          </view>
        </view>
        <view class="dialog-footer">
          <button class="dialog-btn cancel" @click="handleCancelReward">
            取消
          </button>
          <button class="dialog-btn normal" @click="handleNormalPost">
            我就随便写写，不需要奖励
          </button>
          <button class="dialog-btn confirm" @click="handleGoodPost">
            这是好帖，给我奖励！
          </button>
        </view>
      </view>
    </view>

    <!-- 活跃度提示组件 -->
    <ActivityTip
      v-if="showTip"
      :points="tipPoints"
      :description="tipDescription"
    />
  </view>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, watch } from "vue";
import api from "@/api";
import {
  showLoading,
  hideLoading,
  showError,
  showSuccess,
} from "@/utils/common";
import FeatherIcon from "@/components/FeatherIcon.vue";
import { getApiKey } from "@/api/request";
import { getAppVersion } from "@/config/app";
import ActivityTip from "@/components/ActivityTip.vue";
import activityManager from "@/utils/activityManager";
import { chooseAndUploadImage } from "@/utils/upload";

// 表单数据
const formData = reactive({
  articleTitle: "",
  articleContent: "",
  articleTags: "",
  articleType: 0, // 默认normal
  articleShowInList: 1, // 默认真
  articleCommentable: true, // 默认真
  articleAnonymous: false, // 默认假
  articleNotifyFollowers: false, // 默认假
  articleIsOriginal: true, // 默认为原创
  isGoodArticle: "no",
  articleRewardContent: "",
  articleRewardPoint: "",
});

// 积分奖励弹窗
const showRewardDialog = ref(false);

// 编辑器相关状态
const isPreview = ref(false);
const cursorPosition = ref(0);

// 草稿相关状态
const draftCount = ref(0);
const currentDraftId = ref(null);

// 活跃度提示相关
const showTip = ref(false);
const tipPoints = ref(0);
const tipDescription = ref("");

// 标签相关状态
const tagInput = ref("");
const selectedTags = ref([]);
const historicalTags = ref([]);
const recommendedTags = ref([
  "技术",
  "生活",
  "学习",
  "分享",
  "美食",
  "旅行",
  "读书",
  "随笔",
  "编程",
  "创作",
]);

// 监听选中标签的变化，同步到表单数据中
watch(
  selectedTags,
  (newTags) => {
    formData.articleTags = newTags.join(",");
  },
  { deep: true }
);

// 从表单数据中初始化已选标签
watch(
  () => formData.articleTags,
  (newTagsStr) => {
    if (newTagsStr && typeof newTagsStr === "string") {
      const tags = newTagsStr.split(",").filter((tag) => tag.trim() !== "");
      selectedTags.value = tags;
    }
  },
  { immediate: true }
);

// 加载草稿数量
const loadDraftCount = () => {
  try {
    const drafts = uni.getStorageSync("article_drafts") || [];
    draftCount.value = drafts.length;
  } catch (error) {
    console.error("获取草稿数量失败:", error);
    draftCount.value = 0;
  }
};

// 保存草稿
const saveDraft = () => {
  if (!formData.articleTitle && !formData.articleContent) {
    showError("标题和内容都为空，无需保存");
    return;
  }

  try {
    // 获取现有草稿
    let drafts = uni.getStorageSync("article_drafts") || [];

    // 创建新草稿对象
    const draft = {
      id: currentDraftId.value || Date.now().toString(),
      title: formData.articleTitle,
      content: formData.articleContent,
      tags: formData.articleTags,
      createTime: Date.now(),
      updateTime: Date.now(),
    };

    // 如果是编辑现有草稿
    if (currentDraftId.value) {
      const index = drafts.findIndex((d) => d.id === currentDraftId.value);
      if (index !== -1) {
        drafts[index] = draft;
      } else {
        drafts.unshift(draft);
      }
    } else {
      // 新草稿添加到开头
      drafts.unshift(draft);
    }

    // 保存到本地存储
    uni.setStorageSync("article_drafts", drafts);

    // 更新草稿数量
    draftCount.value = drafts.length;

    // 保存当前草稿ID
    currentDraftId.value = draft.id;

    showSuccess("草稿保存成功");
  } catch (error) {
    console.error("保存草稿失败:", error);
    showError("保存草稿失败");
  }
};

// 跳转到草稿页面
const navigateToDrafts = () => {
  // 如果当前有未保存的内容，提示用户
  if (
    (formData.articleTitle || formData.articleContent) &&
    !currentDraftId.value
  ) {
    uni.showModal({
      title: "提示",
      content: "当前内容未保存，是否保存为草稿？",
      success: (res) => {
        if (res.confirm) {
          saveDraft();
        }
        uni.navigateTo({
          url: "/pages/article/drafts",
        });
      },
    });
  } else {
    uni.navigateTo({
      url: "/pages/article/drafts",
    });
  }
};

// 在组件挂载时加载草稿数量和历史标签
onMounted(() => {
  loadDraftCount();
  loadHistoricalTags();

  // 检查是否是编辑草稿
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { draftId, title, tags, type } = currentPage.$page.options;

  // 如果有传入的标题和标签，设置到表单中
  if (title) {
    formData.articleTitle = decodeURIComponent(title);
  }

  if (tags) {
    formData.articleTags = decodeURIComponent(tags);
  }

  if (type) {
    formData.articleType = Number(type);
  }

  if (draftId) {
    // 加载草稿内容
    try {
      const drafts = uni.getStorageSync("article_drafts") || [];
      const draft = drafts.find((d) => d.id === draftId);
      if (draft) {
        currentDraftId.value = draft.id;
        formData.articleTitle = draft.title;
        formData.articleContent = draft.content;
        formData.articleTags = draft.tags;
      }
    } catch (error) {
      console.error("加载草稿失败:", error);
    }
  }
});

// 简单的 Markdown 解析函数
const parseMarkdown = (text) => {
  if (!text) return "";

  // HTML 转义
  const escapeHtml = (str) => {
    const htmlEscapes = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;",
    };
    return str.replace(/[&<>"']/g, (char) => htmlEscapes[char]);
  };

  let html = escapeHtml(text);

  // 处理图片
  html = html.replace(
    /!\[(.*?)\]\((.*?)\)/g,
    '<img src="$2" alt="$1" class="markdown-image">'
  );

  // 处理链接
  html = html.replace(
    /\[(.*?)\]\((.*?)\)/g,
    '<a href="$2" class="markdown-link">$1</a>'
  );

  // 处理标题
  html = html.replace(/^# (.*$)/gm, "<h1>$1</h1>");
  html = html.replace(/^## (.*$)/gm, "<h2>$1</h2>");
  html = html.replace(/^### (.*$)/gm, "<h3>$1</h3>");

  // 处理粗体
  html = html.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>");

  // 处理斜体
  html = html.replace(/\*(.*?)\*/g, "<em>$1</em>");

  // 处理列表
  html = html.replace(/^- (.*$)/gm, "<li>$1</li>");
  html = html.replace(/(<li>.*<\/li>)/gs, "<ul>$1</ul>");

  // 处理段落
  html = html.replace(/\n\n/g, "</p><p>");
  html = html.replace(/^(.+)$/gm, function (match) {
    if (!/^<[h|u|p]/.test(match)) {
      return "<p>" + match + "</p>";
    }
    return match;
  });

  return html;
};

// 预览内容
const previewContent = computed(() => {
  try {
    return parseMarkdown(formData.articleContent);
  } catch (error) {
    console.error("Markdown 转换错误:", error);
    return formData.articleContent;
  }
});

// 切换预览模式
const togglePreview = () => {
  isPreview.value = !isPreview.value;
};

// 处理输入,保存光标位置
const handleInput = (e) => {
  if (e.detail && typeof e.detail.cursor === "number") {
    cursorPosition.value = e.detail.cursor;
  }
};

// 处理获取焦点
const handleFocus = (e) => {
  if (e.detail && typeof e.detail.cursor === "number") {
    cursorPosition.value = e.detail.cursor;
  }
};

// 插入 Markdown 语法
const insertMarkdown = (prefix, suffix) => {
  const content = formData.articleContent || "";
  const position = cursorPosition.value;

  // 在光标位置插入内容
  formData.articleContent =
    content.slice(0, position) + prefix + suffix + content.slice(position);

  // 更新光标位置到插入内容之后
  nextTick(() => {
    cursorPosition.value = position + prefix.length;
  });
};

// 处理图片上传
const handleUploadImage = () => {
  chooseAndUploadImage({
    count: 1,
    loadingText: "图片上传中...",
    successText: "图片上传成功",
  })
    .then((imageUrl) => {
      // 在光标位置插入图片 Markdown 语法
      const imageMarkdown = `![图片](${imageUrl})`;
      const content = formData.articleContent || "";
      const position = cursorPosition.value;

      formData.articleContent =
        content.slice(0, position) + imageMarkdown + content.slice(position);

      // 更新光标位置
      nextTick(() => {
        cursorPosition.value = position + imageMarkdown.length;
      });
    })
    .catch((error) => {
      console.error("上传图片失败:", error);
    });
};

// 关闭积分奖励弹窗
const closeRewardDialog = () => {
  showRewardDialog.value = false;
};

// 取消发布
const handleCancelReward = () => {
  closeRewardDialog();
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  if (!formData.articleTitle.trim()) {
    showError("请输入标题");
    return;
  }
  if (!formData.articleContent.trim()) {
    showError("请输入内容");
    return;
  }
  if (!formData.articleTags.trim()) {
    showError("请输入标签");
    return;
  }

  // 添加水印
  addWatermark();

  // 打赏区验证
  const hasRewardContent = formData.articleRewardContent.trim() !== "";
  const hasRewardPoint = formData.articleRewardPoint.trim() !== "";

  if (hasRewardContent && !hasRewardPoint) {
    showError("请填写打赏积分");
    return;
  }

  if (!hasRewardContent && hasRewardPoint) {
    showError("请填写打赏区内容");
    return;
  }

  // 显示积分奖励提示框
  showRewardDialog.value = true;
};

// 添加水印
const addWatermark = () => {
  // 获取当前APP版本
  const appVersion = getAppVersion();

  // 构建水印文本
  let watermarkText = "";

  // 如果是原创内容，添加原创标题
  if (formData.articleIsOriginal) {
    watermarkText = `\n\n---\n >原创内容 · 版权所有 · 转载请注明出处 \n`;
  } else {
    watermarkText = `\n\n---\n`;
  }
  // 添加来源信息
  watermarkText += ` >本文发自 [摸鱼派APP v${appVersion}](https://fishpi.cn/article/1745833503658)，欢迎下载体验`;

  // 将水印添加到文章内容末尾
  formData.articleContent = formData.articleContent.trim() + watermarkText;
};

// 显示活跃度提示的方法
const showActivityTip = (points, description) => {
  tipPoints.value = points;
  tipDescription.value = description;
  showTip.value = true;

  // 2秒后自动隐藏
  setTimeout(() => {
    showTip.value = false;
  }, 2000);
};

// 处理活跃度记录
const handleActivity = (actionType) => {
  const result = activityManager.recordAction(actionType);
  if (result.success) {
    showActivityTip(result.points, result.description);
  }
};

// 实际发布文章
const submitArticle = async () => {
  try {
    showLoading("发布中...");
    const res = await api.article.addArticle({
      apiKey: getApiKey(),
      articleTitle: formData.articleTitle,
      articleContent: formData.articleContent,
      articleTags: formData.articleTags,
      articleType: formData.articleType,
      articleShowInList: formData.articleShowInList,
      articleCommentable: formData.articleCommentable,
      articleAnonymous: formData.articleAnonymous,
      articleNotifyFollowers: formData.articleNotifyFollowers,
      articleRewardContent: formData.articleRewardContent,
      articleRewardPoint: formData.articleRewardPoint,
      isGoodArticle: formData.isGoodArticle,
      articleIsOriginal: formData.articleIsOriginal,
    });

    if (res.code === 0) {
      // 如果是好帖，记录活跃度
      if (formData.isGoodArticle === "yes") {
        handleActivity("ARTICLE");
      }

      // 删除当前草稿（如果有）
      if (currentDraftId.value) {
        try {
          const drafts = uni.getStorageSync("article_drafts") || [];
          const updatedDrafts = drafts.filter(
            (d) => d.id !== currentDraftId.value
          );
          uni.setStorageSync("article_drafts", updatedDrafts);
          draftCount.value = updatedDrafts.length;
        } catch (error) {
          console.error("删除草稿失败:", error);
        }
      }

      // 跳转到文章详情页
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/article/detail?id=${res.articleId}`,
        });
      }, 1500);
    } else {
      showError(res.msg || "发布失败");
    }
  } catch (error) {
    console.error("发布文章失败:", error);
    showError("发布失败，请稍后重试");
  } finally {
    hideLoading();
  }
};

// 普通发布
const handleNormalPost = () => {
  formData.isGoodArticle = "no";
  closeRewardDialog();
  submitArticle();
};

// 好帖发布
const handleGoodPost = () => {
  formData.isGoodArticle = "yes";
  closeRewardDialog();
  submitArticle();
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 添加标签
const addTag = () => {
  const tag = tagInput.value.trim();
  if (
    tag &&
    !selectedTags.value.includes(tag) &&
    selectedTags.value.length < 4
  ) {
    selectedTags.value.push(tag);

    // 添加到历史标签
    if (!historicalTags.value.includes(tag)) {
      historicalTags.value.unshift(tag);
      if (historicalTags.value.length > 10) {
        historicalTags.value.pop();
      }
      saveHistoricalTags();
    }

    tagInput.value = "";
  } else if (selectedTags.value.length >= 4) {
    showError("最多只能添加4个标签");
  }
};

// 标签输入框失焦处理
const handleTagInputBlur = () => {
  if (tagInput.value.trim() !== "") {
    addTag();
  }
};

// 移除标签
const removeTag = (index) => {
  selectedTags.value.splice(index, 1);
};

// 选择推荐或历史标签
const selectTag = (tag) => {
  if (!selectedTags.value.includes(tag) && selectedTags.value.length < 4) {
    selectedTags.value.push(tag);

    // 如果是历史标签，调整顺序
    const historyIndex = historicalTags.value.indexOf(tag);
    if (historyIndex > -1) {
      historicalTags.value.splice(historyIndex, 1);
      historicalTags.value.unshift(tag);
      saveHistoricalTags();
    }
    // 如果是推荐标签且不在历史中，添加到历史
    else if (!historicalTags.value.includes(tag)) {
      historicalTags.value.unshift(tag);
      if (historicalTags.value.length > 10) {
        historicalTags.value.pop();
      }
      saveHistoricalTags();
    }
  } else if (selectedTags.value.length >= 4) {
    showError("最多只能添加4个标签");
  }
};

// 保存历史标签到缓存
const saveHistoricalTags = () => {
  try {
    uni.setStorageSync("article_historical_tags", historicalTags.value);
  } catch (error) {
    console.error("保存历史标签失败:", error);
  }
};

// 从缓存加载历史标签
const loadHistoricalTags = () => {
  try {
    const tags = uni.getStorageSync("article_historical_tags");
    if (tags && Array.isArray(tags)) {
      historicalTags.value = tags;
    }
  } catch (error) {
    console.error("加载历史标签失败:", error);
  }
};

// 删除单个历史标签
const deleteHistoricalTag = (index) => {
  historicalTags.value.splice(index, 1);
  saveHistoricalTags();
};

// 清空所有历史标签
const clearAllHistoricalTags = () => {
  uni.showModal({
    title: "提示",
    content: "确定要清空所有历史标签吗？",
    success: (res) => {
      if (res.confirm) {
        historicalTags.value = [];
        saveHistoricalTags();
        showSuccess("历史标签已清空");
      }
    },
  });
};
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f5f6f7;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 20rpx 30rpx;
  padding-bottom: 0;
  background-color: #ffffff;
  border-bottom: 1rpx solid #eeeeee;
  position: relative;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: sticky;
  top: 0;
  z-index: 100;
  padding-top: 50rpx;

  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }

  .draft-btn {
    font-size: 28rpx;
    color: #666;
    padding: 10rpx 20rpx;
    border-radius: 30rpx;
    background-color: #f5f5f5;
    margin-left: auto;

    &:active {
      background-color: #e0e0e0;
    }
  }
}

.content {
  flex: 1;
  height: 0;
  padding-bottom: 128rpx;
}

.form-container {
  padding: 20rpx;
  width: 100%;
  box-sizing: border-box;
}

.form-item {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;

  .title-input {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    height: 80rpx;
    width: 100%;
    box-sizing: border-box;
  }

  .content-textarea {
    width: 100%;
    min-height: 500rpx;
    padding: 20rpx;
    font-size: 28rpx;
    line-height: 1.6;
    color: #333;
    background-color: #fff;
    box-sizing: border-box;
    word-break: break-all;
    white-space: pre-wrap;
  }

  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    display: block;
  }

  .tags-tip {
    font-size: 24rpx;
    color: #999;
    margin-left: 16rpx;
  }
}

.tags-item {
  .tags-header {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;
  }

  .tags-input {
    height: 80rpx;
    background-color: #f8f8f8;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    margin-bottom: 16rpx;
  }

  .selected-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-bottom: 16rpx;

    .tag-item {
      display: flex;
      align-items: center;
      background-color: #ff9800;
      color: white;
      padding: 8rpx 16rpx;
      border-radius: 30rpx;
      font-size: 24rpx;

      .tag-remove {
        margin-left: 8rpx;
        width: 36rpx;
        height: 36rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.2);

        &:active {
          background-color: rgba(255, 255, 255, 0.4);
        }
      }
    }
  }

  .tags-suggestion {
    margin-top: 24rpx;

    .suggestion-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12rpx;

      .clear-all {
        font-size: 24rpx;
        color: #999;
        padding: 4rpx 12rpx;

        &:active {
          color: #ff9800;
        }
      }
    }

    .suggestion-title {
      font-size: 26rpx;
      margin-bottom: 10rpx;
      color: #666;
    }

    .suggestion-list {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;
      margin-bottom: 24rpx;

      .suggestion-tag {
        background-color: #f0f0f0;
        color: #333;
        padding: 8rpx 20rpx;
        border-radius: 30rpx;
        font-size: 24rpx;
        display: flex;
        align-items: center;

        .delete-tag {
          margin-left: 8rpx;
          width: 32rpx;
          height: 32rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #999;

          &:active {
            color: #ff9800;
          }
        }

        &:active {
          background-color: #e0e0e0;
        }
      }
    }
  }
}

.basic-settings {
  .radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
  }

  .radio-item {
    flex: 1;
    min-width: 200rpx;
    display: flex;
    align-items: center;
    padding: 16rpx 0;

    .radio-label {
      font-size: 28rpx;
      color: #333;
      margin-left: 10rpx;
    }
  }
}

.reward-settings {
  .reward-content {
    margin-top: 20rpx;
    margin-bottom: 20rpx;
  }

  .reward-textarea {
    width: 100%;
    height: 200rpx;
    border-radius: 8rpx;
    padding: 20rpx;
    font-size: 28rpx;
    background-color: #f8f8f8;
    box-sizing: border-box;
    border: none;
    resize: none;
  }

  .reward-point {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .reward-label {
      font-size: 28rpx;
      color: #333;
    }

    .point-input {
      width: 200rpx;
      height: 60rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      text-align: right;
      border: none;
    }
  }
}

.bottom-bar {
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;

  .btn-group {
    display: flex;
    gap: 20rpx;
  }

  .draft-save-btn {
    flex: 1;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    background-color: #f5f5f5;
    color: #666;
    border-radius: 8rpx;
    font-size: 32rpx;

    &:active {
      background-color: #e0e0e0;
    }
  }

  .submit-btn {
    flex: 2;
    background-color: #ff9800;
    color: #fff;
    border-radius: 8rpx;
    font-size: 32rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;

    &:active {
      opacity: 0.9;
    }
  }
}

.reward-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;

  .dialog-content {
    width: 80%;
    max-height: 80vh;
    background-color: #fff;
    border-radius: 12rpx;
    overflow: hidden;
  }

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid #f0f0f0;

    .dialog-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .close-btn {
      padding: 10rpx;
    }
  }

  .dialog-body {
    padding: 30rpx;
    max-height: 60vh;
    overflow-y: auto;
  }

  .reward-info {
    .reward-title {
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
      margin-bottom: 20rpx;
      display: block;
    }

    .reward-section {
      margin-bottom: 20rpx;

      .section-title {
        font-size: 28rpx;
        color: #ff9800;
        font-weight: bold;
        display: block;
      }

      .section-content {
        font-size: 26rpx;
        color: #666;
        line-height: 1.6;
      }
    }

    .reward-note {
      font-size: 26rpx;
      color: #ff9800;
      line-height: 1.6;
      margin-top: 20rpx;
      display: block;
    }
  }

  .dialog-footer {
    display: flex;
    padding: 20rpx 30rpx;
    border-top: 1px solid #f0f0f0;
    flex-wrap: wrap;
    gap: 20rpx;

    .dialog-btn {
      flex: 1;
      min-width: 200rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      border-radius: 8rpx;

      &.cancel {
        background-color: #f5f5f5;
        color: #666;
      }

      &.normal {
        background-color: #f5f5f5;
        color: #666;
      }

      &.confirm {
        background-color: #ff9800;
        color: #fff;
      }
    }
  }
}

/* 编辑器工具栏样式 */
.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx;
  background-color: #f8f9fa;
  border: 1px solid #eee;
  border-top: none;
  border-radius: 0 0 8rpx 8rpx;
}

.toolbar-left {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.toolbar-btn {
  padding: 12rpx;
  margin-right: 8rpx;
  border-radius: 4rpx;
  cursor: pointer;

  &:hover {
    background-color: #eee;
  }

  &:active {
    background-color: #e0e0e0;
  }
}

.code-block-btn {
  font-family: monospace;
  font-size: 24rpx;
  font-weight: bold;
  color: #666;
}

.preview-btn {
  padding: 8rpx 20rpx;
  background-color: #f0f0f0;
  border-radius: 30rpx;
  font-size: 24rpx;
  color: #666;

  &:active {
    background-color: #e0e0e0;
  }
}

.editor-container {
  border: 1px solid #eee;
  border-radius: 8rpx 8rpx 0 0;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;

  :deep(.uni-textarea-wrapper) {
    width: 100% !important;
    box-sizing: border-box;
    padding: 0;
  }

  :deep(.uni-textarea-placeholder) {
    font-size: 28rpx;
    color: #999;
  }

  :deep(.uni-textarea-textarea) {
    width: 100% !important;
    box-sizing: border-box;
    padding: 20rpx;
  }
}

.preview-container {
  padding: 20rpx;
  min-height: 400rpx;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8rpx;
  width: 100%;
  box-sizing: border-box;
}

.preview-content {
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;

  :deep(h1) {
    font-size: 40rpx;
    font-weight: bold;
    margin: 24rpx 0;
  }

  :deep(h2) {
    font-size: 36rpx;
    font-weight: bold;
    margin: 20rpx 0;
  }

  :deep(h3) {
    font-size: 32rpx;
    font-weight: bold;
    margin: 16rpx 0;
  }

  :deep(p) {
    margin: 16rpx 0;
  }

  :deep(ul) {
    padding-left: 40rpx;
    margin: 16rpx 0;
  }

  :deep(li) {
    margin: 8rpx 0;
    list-style: disc;
  }

  :deep(strong) {
    font-weight: bold;
  }

  :deep(em) {
    font-style: italic;
  }
}

.content-item {
  width: 100%;
  box-sizing: border-box;
}

/* Markdown 样式优化 */
.markdown-link {
  color: #0072ff;
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }
}

.markdown-image {
  max-width: 100%;
  height: auto;
  border-radius: 8rpx;
  margin: 16rpx 0;
}

.markdown-code {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 8rpx;
  overflow-x: auto;
  margin: 16rpx 0;
  font-family: monospace;
  font-size: 24rpx;
  line-height: 1.5;
}
</style>
